<!--
 * @Autor: ZhangYao
 * @Date: 2023-02-27 10:12:18
 * @LastEditors: ZhangYao
 * @LastEditTime: 2023-03-03 17:16:02
-->
<template>
  <el-dialog
    v-model="visible"
    fullscreen
    destroy-on-close
  >
    <div class="jar-page">
      <div class="params-panel">
        <el-row class="jarmain">
          <el-col :span="23" class="jartitle">
            作业开发【{{ form.name }}】
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="4">
            <el-upload
              v-if="form.jarId === ''"
              ref="upload"
              action=""
              :auto-upload="true"
              accept=".jar"
              :style="{ height: '100%' }"
              drag
              :limit="1"
              :http-request="httpRequest"
              :show-file-list="false"
              :disabled="step === 4"
            >
              <div>
                <i class="el-icon-upload"/>
                <div v-if="step === 4" class="el-upload__text">
                  <p>作业维护中...</p>
                  请点击右上角编辑按钮，进入编辑状态
                </div>
                <div v-else class="el-upload__text">
                  <p>仅支持上传jar包</p>
                  将文件拖到此处，或<em>点击上传</em>
                </div>
              </div>
            </el-upload>
            <div v-else class="upload-success">
              <IconFont class="icon-Check" type="icon-Check"/>
              <div class="el-upload__text">
                <p>
                  {{ form.jarFileName }}
                  <i v-if="step !== 4" class="el-icon-delete" @click="deleteFile"/>
                </p>
              </div>
            </div>
          </el-col>

          <el-col :span="9">
            <el-form ref="form" label-position="top" :model="form" :rules="rules" :disabled="step === 4">
              <el-row type="flex" justify="space-between">
                <el-col :span="11">
                  <el-form-item label="作业名" prop="name">
                    <el-input v-model="form.name" readonly/>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="执行模式" prop="type">
                    <el-select
                      v-model="form.type"
                      placeholder="请选择执行模式"
                      :style="{ width: '100%' }"
                    >
                      <el-option
                        v-for="item in modeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row/>
            </el-form>
            <el-form
              ref="form"
              :model="form"
              label-position="left"
              :rules="rules"
              :disabled="step === 4"
            >
            </el-form>
            <el-form ref="form" label-position="top" :model="form" :rules="rules" :disabled="step === 4">
              <el-row>
                <el-row type="flex" justify="space-between">
                  <el-col :span="11">
                    <el-form-item label="SavePoint策略" prop="savePointStrategy">
                      <el-select
                        v-model="form.savePointStrategy"
                        placeholder="请选择SavePoint策略"
                        :style="{ width: '100%' }"
                      >
                        <el-option
                          v-for="item in savepointsOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-row>
            </el-form>
          </el-col>
          <el-col :span="9">
            <el-form ref="form" :model="form" :rules="rules" :disabled="step === 4">
              <el-form-item>
                <el-row type="flex" justify="end">
                  <el-col :span="8">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="保存"
                      placement="top"
                    >
                      <IconFont
                        class="client_icon2"
                        type="icon-save"
                        @click="saveWorkFn()"
                      />
                    </el-tooltip>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="提交"
                      placement="top"
                    >
                      <IconFont
                        class="client_icon2"
                        type="icon-submit"
                        @click="jobSubmitFn()"
                      />
                    </el-tooltip>
                    <el-tooltip
                      v-if="step === 2"
                      class="item"
                      effect="dark"
                      content="发布"
                      placement="top"
                    >
                      <IconFont
                        class="client_icon2"
                        type="icon-release"
                        @click="releaseFn()"
                      />
                    </el-tooltip>
                    <el-tooltip
                      v-if="step === 4"
                      class="item"
                      effect="dark"
                      content="维护，点击进入编辑状态"
                      placement="top"
                    >
                      <IconFont
                        class="client_icon2"
                        type="icon-edit"
                        @click="editFn()"
                      />
                    </el-tooltip>
                    <el-tooltip
                      v-if="step === 4"
                      class="item"
                      effect="dark"
                      content="上线，上线后自动恢复、告警等将生效"
                      placement="top"
                    >
                      <IconFont
                        class="client_icon2"
                        type="icon-workOnline"
                        @click="onlineFn()"
                      />
                    </el-tooltip>
                    <el-tooltip
                      v-if="step === 5"
                      class="item"
                      effect="dark"
                      content="下线，将进入最新发布状态"
                      placement="top"
                    >
                      <IconFont
                        class="client_icon2"
                        type="icon-download"
                        @click=" offlineFn()"
                      />
                    </el-tooltip>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div class="table-panel">
        <el-tabs
          v-model="activeName"
          type="border-card"
          :style="{ marginTop: '15px' }"
          @tab-click="tabhandleClick"
          v-if="visible"
        >
          <el-tab-pane label="进程" name="process">
            <process :taskId="form.taskId"/>
          </el-tab-pane>
          <el-tab-pane label="历史" name="history">
            <History/>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import IconFont from '../components/iconFont.vue'
import routeConfig from '../mixins/routeConfig'
import mixins from './mixins'
import {
  queryTaskParams,
  saveWork,
  submitWork,
  releaseWork,
  developWork,
  onlineWork,
  offlineWork,
  queryListJobs
} from '../api/workDevelopment'
import { upJar, deleteJar } from '../api/workManage'
import Process from '../components/process.vue'
import History from '../components/history.vue'
export default {
  name: 'JarDevelopmentPage',
  components: {
    IconFont,
    Process,
    History
  },
  mixins: [routeConfig, mixins],
  data() {
    const form = this.initForm()
    const rules = this.initRules()

    return {
      query: {},
      visible: false,
      // 进程选择的集群
      clusterId: '',
      // 后端暂时没有翻页
      pagination: {
        total: 0,
        page: 1
      },
      // 执行模式暂时前端写死
      modeOptions: [
        { label: 'Local', value: 'local', disabled: true },
        { label: 'Standalone', value: 'standalone', disabled: true },
        { label: 'Yarn Session', value: 'yarn-session', disabled: true },
        { label: 'Yarn Per-Job', value: 'yarn-per-job', disabled: true },
        { label: 'Yarn Application', value: 'yarn-application' }
      ],
      // 集群后端接口获取
      flinkOptions: [],
      // savepoints策略前端写死
      savepointsOptions: [
        { label: '禁用', value: 0 },
        { label: '最近一次', value: 1 },
        { label: '最早一次', value: 2 },
        { label: '指定一次', value: 3 }
      ],
      // 进程表格
      tableData: [],
      // 整个表单form
      form: form,
      // 整个表单校验
      rules: rules,
      // 其他配置的列表
      configList: [{ key: '', value: '' }],
      // 控制tab，优先显示进程
      activeName: 'process',
      // 当前作业步骤
      step: 0
    }
  },
  watch: {
    // 进程tab里面，选择集群id，获取进程列表
    clusterId: {
      handler() {
        this.getProcess()
      }
    }
  },
  created() {

  },
  methods: {
    init(query) {
      this.visible = true;
      if (
        query.id
      ) {
        this.query = query;
        this.form.taskId = query.id
        this.form.name = query.jobName
      } else {
        this.$message({
          message: '作业id获取失败',
          type: 'error'
        })
      }
      this.queryTaskParamsHandle()
    },
    // 下线，将进入最新发布状态
    offlineFn() {
      this.$confirm(`确定下线作业【${this.form.name}】吗?`, '下线作业', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          offlineWork({ id: this.form.taskId, type: 'cancel' }).then((res) => {
            if (res) {
              this.$message({
                message: `下线作业【${this.form.name}】成功`,
                type: 'success'
              })
              this.queryTaskParamsHandle()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 上线，上线后自动恢复、告警等将生效
    onlineFn() {
      this.$confirm(`确定上线作业【${this.form.name}】吗?`, '上线作业', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          onlineWork({ id: this.form.taskId }).then((res) => {
            if (res) {
              this.$message({
                message: `上线作业【${this.form.name}】成功`,
                type: 'success'
              })
              this.queryTaskParamsHandle()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 维护，点击进入编辑状态
    editFn() {
      this.$confirm(`确定维护作业【${this.form.name}】吗?`, '维护作业', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          developWork({ id: this.form.taskId }).then((res) => {
            if (res) {
              this.$message({
                message: `维护作业【${this.form.name}】成功`,
                type: 'success'
              })
              this.queryTaskParamsHandle()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 作业提交
    jobSubmitFn() {
      submitWork({ id: this.form.taskId }).then((res) => {
        if (res) {
          this.$message({
            message: '提交成功',
            type: 'success'
          })
        }
      })
    },
    // 作业发布
    releaseFn() {
      releaseWork({ id: this.form.taskId }).then((res) => {
        if (res) {
          this.queryTaskParamsHandle()
          this.$message({
            message: '发布成功',
            type: 'success'
          })
        }
      })
    },
    // 获取进程列表
    getProcess() {
      queryListJobs({ clusterId: this.clusterId }).then((data) => {
        if (data) {
          this.tableData = data
        }
      })
    },
    // 保存作业
    saveWorkFn() {
      this.form.config = this.configList
      console.log(this.form)
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false
        } else {
          saveWork(this.form).then((data) => {
            if (data) {
              this.queryTaskParamsHandle()
              this.$message({
                message: '保存成功',
                type: 'success'
              })
            }
          })
        }
      })
    },
    // 查群集群列表
    async queryTaskParamsHandle() {
      const res = await queryTaskParams({
        taskId: this.form.taskId
      })
      this.step = res.defaultTaskData.step ? res.defaultTaskData.step : ''
      this.form = this.initForm(res.defaultTaskData, this.query.id)
      this.flinkOptions = res.clusterConfigurationData.map((item) => {
        return {
          type: item.type,
          label: item.name,
          value: item.id
        }
      })
    },
    // 删除文件
    deleteFile() {
      this.form.jarId = ''
      this.form.jarFileName = ''
      deleteJar({ taskId: this.form.taskId }).then((data) => {
        if (data) {
          this.queryTaskParamsHandle()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
      })
    },
    // 上传
    httpRequest(file) {
      console.log(file)
      const params = new FormData()
      params.append('file', file.file)
      params.append('id', this.query.id)
      params.append('jarId', this.form.jarId)
      upJar(params).then((data) => {
        if (data) {
          this.queryTaskParamsHandle()
          this.$message({
            message: '上传成功',
            type: 'success'
          })
        } else {
          this.form.jarId = ''
          this.form.jarFileName = ''
        }
      })
    },
    // 删除配置项
    deleteConfig(index) {
      this.configList.splice(index, 1)
    },
    // 增加配置项
    addConfig() {
      this.configList.push({
        key: '',
        value: ''
      })
    },
    // 根据不同的类型拉不同的列表
    tabhandleClick(value) {
      console.log(value)
    },
    // 改变分页器数量
    pageSizeChangeHandler(value) {
      console.log(value)
    },
    // 改变页码
    pageChangeHandler(value) {
      console.log(value)
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.el-upload) {
  width: 100%;
  height: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .el-icon-upload {
    margin-top: 0px;
  }
}

.client_icon2 {
  width: 20px;
  height: 20px;
  margin: 0px 8px;
  cursor: pointer;
}

.jartitle {
  height: 40px;
}

.jar-page {
  height: calc(100vh - 160px);

  .params-panel {
    height: 470px;
  }

  .table-panel {
    height: calc(100vh - 630px);
    overflow-y: scroll;
  }

  .config-box {
    height: 220px;
    overflow-y: scroll;
  }
  .icon-Check {
    width: 100px;
    height: 100px;
    fill: rgb(19, 206, 102);
  }

  .upload-success {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 1px solid #ccc;
    .el-icon-delete {
      cursor: pointer;
      &:hover {
        color: red;
      }
    }
  }
}
</style>
